package com.xiyu.service.repository.mailbox.signature;

import com.xiyu.service.model.mailbox.account.MailboxAccountFetcher;
import com.xiyu.service.model.mailbox.signature.*;
import org.babyfish.jimmer.spring.repository.JRepository;

import java.util.Optional;
import java.util.List;

public interface MailboxAccountSignatureRepository extends JRepository<MailboxAccountSignature, Long> {
    MailboxAccountSignatureTable mailboxAccountSignatureTable = MailboxAccountSignatureTable.$;

    default List<MailboxAccountSignature> findByOwnerId(Long ownerId){
        return sql().createQuery(mailboxAccountSignatureTable)
                .where(mailboxAccountSignatureTable.account().ownerId().eq(ownerId))
                .select(mailboxAccountSignatureTable.fetch(
                        MailboxAccountSignatureFetcher.$.allTableFields()
                                .account(MailboxAccountFetcher.$.showName())
                ))
                .execute();
    }

    default void updateByDeleteSignatureId(Long ownerId, Long signatureId){
        sql().createUpdate(mailboxAccountSignatureTable)
                .set(mailboxAccountSignatureTable.newMailSignatureId(), 0L)
                .where(mailboxAccountSignatureTable.account().ownerId().eq(ownerId))
                .where(mailboxAccountSignatureTable.newMailSignatureId().eq(signatureId))
                .execute();

        sql().createUpdate(mailboxAccountSignatureTable)
                .set(mailboxAccountSignatureTable.replyMailSignatureId(), 0L)
                .where(mailboxAccountSignatureTable.account().ownerId().eq(ownerId))
                .where(mailboxAccountSignatureTable.replyMailSignatureId().eq(signatureId))
                .execute();
    }

    default Optional<MailboxAccountSignature> findByAccountId(Long accountId){
        return sql().createQuery(mailboxAccountSignatureTable)
                .where(mailboxAccountSignatureTable.accountId().eq(accountId))
                .select(mailboxAccountSignatureTable.fetch(
                        MailboxAccountSignatureFetcher.$.allTableFields()
                                .newMailSignature(MailboxMailSignatureFetcher.$.content())
                                .replyMailSignature(MailboxMailSignatureFetcher.$.content())
                )).fetchOptional();
    };

}